
jQuery.extend({


    createUploadIframe: function (id, uri) {//idÎªµ±Ç°ÏµÍ³Ê±¼ä×Ö·û´®£¬uriÊÇÍâ²¿´«ÈëµÄjson¶ÔÏóµÄÒ»¸ö²ÎÊý
        //create frame
        var frameId = 'jUploadFrame' + id; //¸øiframeÌí¼ÓÒ»¸ö¶ÀÒ»ÎÞ¶þµÄid
        var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //´´½¨iframeÔªËØ
        if (window.ActiveXObject) {//ÅÐ¶Ïä¯ÀÀÆ÷ÊÇ·ñÖ§³ÖActiveX¿Ø¼þ
            if (typeof uri == 'boolean') {
                iframeHtml += ' src="' + 'javascript:false' + '"';

            }
            else if (typeof uri == 'string') {
                iframeHtml += ' src="' + uri + '"';
            }
        }
        iframeHtml += ' />';
        jQuery(iframeHtml).appendTo(document.body); //½«¶¯Ì¬iframe×·¼Óµ½bodyÖÐ

        return jQuery('#' + frameId).get(0); //·µ»Øiframe¶ÔÏó
    },
    createUploadForm: function (id, fileElementId, data) {//idÎªµ±Ç°ÏµÍ³Ê±¼ä×Ö·û´®£¬fileElementIdÎªÒ³Ãæ<input type='file' />µÄid£¬dataµÄÖµÐèÒª¸ù¾Ý´«ÈëjsonµÄ¼üÀ´¾ö¶¨
        //create form	
        var formId = 'jUploadForm' + id; //¸øformÌí¼ÓÒ»¸ö¶ÀÒ»ÎÞ¶þµÄid
        var fileId = 'jUploadFile' + id; //¸ø<input type='file' />Ìí¼ÓÒ»¸ö¶ÀÒ»ÎÞ¶þµÄid
        var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //´´½¨formÔªËØ
        if (data) {//Í¨³£Îªfalse
            for (var i in data) {
                jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //¸ù¾ÝdataµÄÄÚÈÝ£¬´´½¨Òþ²ØÓò£¬Õâ²¿·ÖÎÒ»¹²»ÖªµÀÊÇÊ²Ã´Ê±ºòÓÃµ½¡£¹À¼ÆÊÇ´«ÈëjsonµÄÊ±ºò£¬Èç¹ûÄ¬ÈÏ´«Ò»Ð©²ÎÊýµÄ»°ÒªÓÃµ½¡£
            }
        }
        var oldElement = jQuery('#' + fileElementId); //µÃµ½Ò³ÃæÖÐµÄ<input type='file' />¶ÔÏó
        var newElement = jQuery(oldElement).clone(); //¿ËÂ¡Ò³ÃæÖÐµÄ<input type='file' />¶ÔÏó
        jQuery(oldElement).attr('id', fileId); //ÐÞ¸ÄÔ­¶ÔÏóµÄid
        jQuery(oldElement).before(newElement); //ÔÚÔ­¶ÔÏóÇ°²åÈë¿ËÂ¡¶ÔÏó
        jQuery(oldElement).appendTo(form); //°ÑÔ­¶ÔÏó²åÈëµ½¶¯Ì¬formµÄ½áÎ²´¦



        //set attributes
        jQuery(form).css('position', 'absolute'); //¸ø¶¯Ì¬formÌí¼ÓÑùÊ½£¬Ê¹Æä¸¡¶¯ÆðÀ´£¬
        jQuery(form).css('top', '-1200px');
        jQuery(form).css('left', '-1200px');
        jQuery(form).appendTo('body'); //°Ñ¶¯Ì¬form²åÈëµ½bodyÖÐ
        return form;
    },

    ajaxFileUpload: function (s) {//ÕâÀïsÊÇ¸öjson¶ÔÏó£¬´«ÈëÒ»Ð©ajaxµÄ²ÎÊý
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s); //´ËÊ±µÄs¶ÔÏóÊÇÓÉjQuery.ajaxSettingsºÍÔ­s¶ÔÏóÀ©Õ¹ºóµÄ¶ÔÏó
        var id = new Date().getTime(); //È¡µ±Ç°ÏµÍ³Ê±¼ä£¬Ä¿µÄÊÇµÃµ½Ò»¸ö¶ÀÒ»ÎÞ¶þµÄÊý×Ö
        var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //´´½¨¶¯Ì¬form
        var io = jQuery.createUploadIframe(id, s.secureuri); //´´½¨¶¯Ì¬iframe
        var frameId = 'jUploadFrame' + id; //¶¯Ì¬iframeµÄid
        var formId = 'jUploadForm' + id; //¶¯Ì¬formµÄid
        // Watch for a new set of requests
        if (s.global && !jQuery.active++) {//µ±jQuery¿ªÊ¼Ò»¸öajaxÇëÇóÊ±·¢Éú
            jQuery.event.trigger("ajaxStart"); //´¥·¢ajaxStart·½·¨
        }
        var requestDone = false; //ÇëÇóÍê³É±êÖ¾
        // Create the request object
        var xml = {};
        if (s.global)
            jQuery.event.trigger("ajaxSend", [xml, s]); //´¥·¢ajaxSend·½·¨
        // Wait for a response to come back
        var uploadCallback = function (isTimeout) {//»Øµ÷º¯Êý
            var io = document.getElementById(frameId); //µÃµ½iframe¶ÔÏó
            try {
                if (io.contentWindow) {//¶¯Ì¬iframeËùÔÚ´°¿Ú¶ÔÏóÊÇ·ñ´æÔÚ
                    xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
                    xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;

                } else if (io.contentDocument) {//¶¯Ì¬iframeµÄÎÄµµ¶ÔÏóÊÇ·ñ´æÔÚ
                    xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
                    xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
                }
            } catch (e) {
                jQuery.handleError(s, xml, null, e);
            }
            if (xml || isTimeout == "timeout") {//xml±äÁ¿±»¸³Öµ»òÕßisTimeout == "timeout"¶¼±íÊ¾ÇëÇó·¢³ö£¬²¢ÇÒÓÐÏìÓ¦
                requestDone = true; //ÇëÇóÍê³É
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error"; //Èç¹û²»ÊÇ¡°³¬Ê±¡±£¬±íÊ¾ÇëÇó³É¹¦
                    // Make sure that the request was successful or notmodified
                    if (status != "error") {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData(xml, s.dataType); //¸ù¾Ý´«ËÍµÄtypeÀàÐÍ£¬·µ»Øjson¶ÔÏó£¬´ËÊ±·µ»ØµÄdata¾ÍÊÇºóÌ¨²Ù×÷ºóµÄ·µ»Ø½á¹û
                        // If a local callback was specified, fire it and pass it the data
                        if (s.success)
                            s.success(data, status); //Ö´ÐÐÉÏ´«³É¹¦µÄ²Ù×÷

                        // Fire the global callback
                        if (s.global)
                            jQuery.event.trigger("ajaxSuccess", [xml, s]);
                    } else
                        jQuery.handleError(s, xml, status);
                } catch (e) {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if (s.global)
                    jQuery.event.trigger("ajaxComplete", [xml, s]);

                // Handle the global AJAX counter
                if (s.global && ! --jQuery.active)
                    jQuery.event.trigger("ajaxStop");

                // Process result
                if (s.complete)
                    s.complete(xml, status);

                jQuery(io).unbind();//ÒÆ³ýiframeµÄÊÂ¼þ´¦Àí³ÌÐò

                setTimeout(function () {//ÉèÖÃ³¬Ê±Ê±¼ä
                    try {
                        jQuery(io).remove();//ÒÆ³ý¶¯Ì¬iframe
                        jQuery(form).remove();//ÒÆ³ý¶¯Ì¬form

                    } catch (e) {
                        jQuery.handleError(s, xml, null, e);
                    }

                }, 100)

                xml = null

            }
        }
        // Timeout checker
        if (s.timeout > 0) {//³¬Ê±¼ì²â
            setTimeout(function () {
                // Check to see if the request is still happening
                if (!requestDone) uploadCallback("timeout");//Èç¹ûÇëÇóÈÔÎ´Íê³É£¬¾Í·¢ËÍ³¬Ê±ÐÅºÅ
            }, s.timeout);
        }
        try {

            var form = jQuery('#' + formId);
            jQuery(form).attr('action', s.url);//´«ÈëµÄajaxÒ³Ãæµ¼Ïòurl
            jQuery(form).attr('method', 'POST');//ÉèÖÃÌá½»±íµ¥·½Ê½
            jQuery(form).attr('target', frameId);//·µ»ØµÄÄ¿±êiframe£¬¾ÍÊÇ´´½¨µÄ¶¯Ì¬iframe
            if (form.encoding) {//Ñ¡Ôñ±àÂë·½Ê½
                jQuery(form).attr('encoding', 'multipart/form-data');
            }
            else {
                jQuery(form).attr('enctype', 'multipart/form-data');
            }
            jQuery(form).submit();//Ìá½»form±íµ¥

        } catch (e) {
            jQuery.handleError(s, xml, null, e);
        }

        jQuery('#' + frameId).load(uploadCallback); //ajax ÇëÇó´Ó·þÎñÆ÷¼ÓÔØÊý¾Ý£¬Í¬Ê±´«Èë»Øµ÷º¯Êý
        return { abort: function () { } };

    },

    uploadHttpData: function (r, type) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if (type == "script")
            jQuery.globalEval(data);
        // Get the JavaScript object, if JSON is used.
        if (type == "json")
            eval("data = " + data);
        // evaluate scripts within html
        if (type == "html")
            jQuery("<div>").html(data).evalScripts();

        return data;
    }
})

